<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>试验报名 - {{trial.trial_name}}</title>
    <link href="/apps/css/bootstrap.min.css" rel="stylesheet">
    <link href="/apps/css/fontawesome-free-6.4.0-web/css/all.css" rel="stylesheet">
    <script src="/apps/js/baidu-tongji-mtx.js"></script>
</head>
<body>
    <div class="container py-4">
        <div class="row mb-4">
            <div class="col">
                <h2>
                    <a href="/apps/trial" class="text-decoration-none">临床研究支持</a>
                    <i class="bi bi-chevron-right"></i>
                    试验报名
                </h2>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-body">
                <h3 class="card-title">{{trial.trial_name}}</h3>
                <div class="card-text mb-3">{{{trial.description}}}</div>
                <div class="row">
                    <div class="col-md-4">
                        <small class="text-muted">试验代码：{{trial.trial_code}}</small>
                    </div>
                    <div class="col-md-4">
                        <small class="text-muted">开始日期：{{trial.start_date}}</small>
                    </div>
                    <div class="col-md-4">
                        <small class="text-muted">结束日期：{{#if trial.end_date}}{{trial.end_date}}{{else}}-{{/if}}</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="text-end mb-3">
            <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#tipsModal">
                <i class="fas fa-info-circle me-1"></i>报名须知
            </button>
        </div>

        <div class="card">
            <div class="card-body">
                <h4 class="card-title mb-4">报名信息</h4>
                <form action="/apps/trial/apply/{{trial.trial_code}}" method="POST" enctype="multipart/form-data" id="applyForm">
                    <input type="hidden" name="applyInfo" id="applyInfoField">

                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">受试者姓名</label>
                            <input type="text" class="form-control" name="subject_name" value="{{user.real_name}}" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">性别</label>
                            <select class="form-select" name="gender" required>
                                <option value="">请选择</option>
                                <option value="1">男</option>
                                <option value="2">女</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">出生日期</label>
                            <input type="date" class="form-control" name="birth_date" required>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">是否已确诊本适应症</label>
                            <select class="form-select" name="is_diagnosed" required>
                                <option value="">请选择</option>
                                <option value="1">是</option>
                                <option value="0">否</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">确诊日期</label>
                            <input type="date" class="form-control" name="diagnosis_date">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">计划面诊日期</label>
                            <div class="text-danger small mb-2">*必须携儿童本人到北京市面诊后才能入组</div>
                            <input type="date" class="form-control" name="planned_visit_date" required>
                            <small class="text-muted">申请入组面诊时间为每周二周三上午，北京儿童医院尹梦雅医生发育行为门诊</small>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">确诊报告及证明</label>
                            <div class="text-danger small mb-2">*必须上传确诊报告及证明</div>
                            <input type="file" class="form-control" id="fileInput" accept=".jpg,.jpeg,.png,.pdf" multiple>
                            <div class="form-text">可以选择多个文件一起上传，支持图片和PDF格式</div>
                            <div id="uploadProgress" class="mt-3 border-top pt-3">
                                <div class="upload-progress"></div>
                                <div class="file-list"></div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">既往病史及手术史</label>
                            <textarea class="form-control" name="medical_history" rows="3" required></textarea>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">既往药物食物过敏史</label>
                            <textarea class="form-control" name="allergy_history" rows="3" required></textarea>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">过去一个月的治疗方案与用药量</label>
                            <textarea class="form-control" name="recent_treatment" rows="3" required></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">过去一个月的康复方案与训练量</label>
                            <textarea class="form-control" name="recent_recover" rows="3" required></textarea>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">当前诊断和治疗机构</label>
                            <input type="text" class="form-control" name="treatment_hospital" required>
                            <small class="text-muted">如无，请填写"无"</small>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">当前康复训练机构</label>
                            <input type="text" class="form-control" name="recover_institution" required>
                            <small class="text-muted">如无，请填写"无"或"家庭"</small>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">联系人姓名</label>
                            <input type="text" class="form-control" name="contact_name" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">与受试者关系</label>
                            <input type="text" class="form-control" name="contact_relation" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">联系人手机</label>
                            <input type="tel" class="form-control" name="contact_phone" value="{{user.phone}}" required>
                        </div>

                        <div class="col-12">
                            <label class="form-label">联系人常住地址</label>
                            <input type="text" class="form-control" name="contact_address" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">报名理由</label>
                            <small class="text-muted">请在此说明符合哪些入组标准</small>
                            <textarea class="form-control" name="apply_reason" rows="3" required></textarea>
                        </div>

                        <div class="col-12">
                            <button type="submit" class="btn btn-primary">提交线上报名</button>
                            <a href="/apps/trial" class="btn btn-secondary">返回应用首页</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="tipsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">报名须知</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    {{{trial.apply_tip}}}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">我已了解</button>
                </div>
            </div>
        </div>
    </div>

    <script src="/apps/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const hasShownTips = sessionStorage.getItem('hasShownTips');
            if (!hasShownTips) {
                const tipsModal = new bootstrap.Modal(document.getElementById('tipsModal'));
                tipsModal.show();
                sessionStorage.setItem('hasShownTips', 'true');
            }
        });

        let uploadedFiles = [];

        document.getElementById('fileInput').addEventListener('change', async function(e) {
            const files = e.target.files;
            const progressDiv = document.getElementById('uploadProgress');
            const progressContainer = progressDiv.querySelector('.upload-progress');

            progressContainer.innerHTML = '<div class="progress" style="height: 20px;"><div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%"></div></div>';
            const progressBar = progressDiv.querySelector('.progress-bar');

            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const formData = new FormData();
                formData.append('file', file);

                try {
                    progressBar.style.width = `${(i / files.length * 100)}%`;
                    progressBar.textContent = `上传中 ${i + 1}/${files.length}`;

                    const response = await fetch('https://mall.totembio.cn/api/uploadMtaFile', {
                        method: 'POST',
                        body: formData
                    });

                    const result = await response.json();
                    console.log('upload result:', result);

                    if (result.status === 200) {
                        uploadedFiles.push({
                            url: result.data.src,
                            name: file.name
                        });
                    } else {
                        throw new Error(result.message || '上传失败啊');
                    }
                } catch (error) {
                    progressContainer.innerHTML = `<div class="alert alert-danger">文件 ${file.name} ${error.message}</div>`;
                    return;
                }
            }

            if (uploadedFiles.length > 0) {
                progressBar.style.width = '100%';
                progressBar.classList.remove('progress-bar-animated');
                progressBar.textContent = '上传完成';
                setTimeout(() => {
                    const progressBarDiv = progressContainer.querySelector('.progress');
                    if (progressBarDiv) {
                        progressBarDiv.style.display = 'none';
                    }
                }, 1000);
                updateFileList();
            }

            e.target.value = '';
        });

        function updateFileList() {
            const progressDiv = document.getElementById('uploadProgress');
            const fileList = progressDiv.querySelector('.file-list');

            fileList.innerHTML = uploadedFiles.map((file, index) => `
                <div class="d-flex align-items-center mb-2 bg-light p-2 rounded">
                    <span class="badge bg-light text-dark me-2">${index + 1}</span>
                    <a href="${file.url}" target="_blank" class="me-2">
                        <i class="fas fa-file"></i> ${file.name}
                    </a>
                    <div class="flex-grow-1"></div>
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeFile(${index})">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            `).join('');

            const statusText = document.createElement('div');
            statusText.className = 'small text-muted mt-2';
            statusText.textContent = `已上传 ${uploadedFiles.length} 个文件`;
            fileList.insertAdjacentElement('afterend', statusText);
        }

        function removeFile(index) {
            uploadedFiles.splice(index, 1);
            updateFileList();
            if (uploadedFiles.length === 0) {
                const progressDiv = document.getElementById('uploadProgress');
                const progressBar = progressDiv.querySelector('.progress');
                if (progressBar) {
                    progressBar.style.display = 'none';
                }
            }
        }

        document.getElementById('applyForm').addEventListener('submit', function(e) {
            e.preventDefault();

            // 检查是否上传了确诊报告
            if (uploadedFiles.length === 0) {
                alert('请上传确诊报告及证明');
                return;
            }

            const formData = new FormData(this);
            const applyInfo = {
                subject_name: formData.get('subject_name'),
                gender: formData.get('gender'),
                birth_date: formData.get('birth_date'),
                is_diagnosed: formData.get('is_diagnosed'),
                diagnosis_date: formData.get('diagnosis_date'),
                diagnosis_files: JSON.stringify(uploadedFiles.map(f => f.url)),
                medical_history: formData.get('medical_history'),
                allergy_history: formData.get('allergy_history'),
                treatment_hospital: formData.get('treatment_hospital'),
                recover_institution: formData.get('recover_institution'),
                recent_treatment: formData.get('recent_treatment'),
                recent_recover: formData.get('recent_recover'),
                contact_name: formData.get('contact_name'),
                contact_relation: formData.get('contact_relation'),
                contact_phone: formData.get('contact_phone'),
                contact_address: formData.get('contact_address'),
                apply_reason: formData.get('apply_reason'),
                planned_visit_date: formData.get('planned_visit_date')
            };

            document.getElementById('applyInfoField').value = JSON.stringify(applyInfo);

            this.submit();
        });
    </script>
</body>
</html> 
